package com.xmg.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.xmg.service.WxService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author xmg
 * @Description
 * @email 463364973@qq.com
 * <p>
 * Date:2019/4/5 15:16
 */
@Controller
public class WxController {

    @Autowired
    private WxService wxService;

    private final  static Logger LOGGER = LoggerFactory.getLogger(WxController.class);

    @GetMapping("/")
    public void get(HttpServletRequest request, HttpServletResponse response) throws IOException {

        /**
         * signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
         * timestamp	时间戳
         * nonce	随机数
         * echostr	随机字符串
         */
        System.out.println("验证消息的确来自微信服务器");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        LOGGER.info("微信加密签名: " + signature + " 时间戳: " + timestamp + " 随机数: " + nonce + " 随机字符串: " + echostr);
        if (WxService.check(signature, timestamp, nonce)){
            PrintWriter pw = response.getWriter();
            pw.print(echostr);
            pw.flush();
            pw.close();
            LOGGER.info("接入成功");
        }else {
            LOGGER.info("接入失败");
        }
    }

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello(){
        return "Hello World!";
    }

    @PostMapping("/")
    public void post(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //testMessage(request);
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        // 处理消息和事件
        Map<String, String> resulMap = WxService.parseReauest(request.getInputStream());
        // 回复消息处理
       String xmlString = WxService.getResponse(resulMap);
        PrintWriter writer = response.getWriter();
        writer.print(xmlString);
        writer.flush();
        writer.close();
        LOGGER.info("用户发来得消息：-->"+ resulMap);
    }

    /**
     * 测试消息接收
     * @param request
     * @throws IOException
     */
    private void testMessage(HttpServletRequest request) throws IOException {
        ServletInputStream is = request.getInputStream();
        byte [] b = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = is.read(b)) != -1){
            sb.append(new String(b,0,len));
        }
        LOGGER.info("接收到客户发来得消息：" + sb.toString());
        JSONObject jsonObject = XML.toJSONObject(sb.toString());
        LOGGER.info(jsonObject.toString());
    }

}
